package org.linloong.modules.apis.disease.controller;

import com.alibaba.fastjson2.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.linloong.config.audio.AudioServerProperties;
import org.linloong.config.audio.DifyAgentProperties;
import org.linloong.core.result.Result;
import org.linloong.utils.CheckLastResultCacheUtil;
import org.linloong.utils.VideoFeedUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Package: org.linloong.modules.apis.disease.controller.DiseaseCameraController
 * @Author: guxin
 * @CreateTime: 2025/10/19 17:44
 * @Description:
 * @Version: 3.0
 */
@Slf4j
@RestController
@RequestMapping("/api/disease/camera")
@RequiredArgsConstructor
@Tag(name = "病虫害-摄像头")
@ApiSupport(order = 201)
public class DiseaseCameraController {
    @Autowired
    private AudioServerProperties serverProperties;
    @Autowired
    private DifyAgentProperties agentProperties;

//    @PostMapping("/start")
//    @Operation(summary = "启动病虫害检测")
//    @ApiOperationSupport(order = 1)
//    public Result<JSONObject> cameraStart(String rtspUrl) {
//        cameraStop();
//        try (HttpResponse response = HttpRequest.post(serverProperties.getDiseaseCameraUrl() + "/api/disease_camera/start_stream")
//                .timeout(30000)
//                .body(new JSONObject() {{
//                    put("rtsp_url", rtspUrl);
//                }}.toJSONString())
//                .execute()) {
//            return Result.success(JSON.parseObject(response.body()));
//        }
//    }
//
//    @PostMapping("/stop")
//    @Operation(summary = "停止病虫害检测")
//    @ApiOperationSupport(order = 2)
//    public Result<Boolean> cameraStop() {
//        try (HttpResponse ignored = HttpRequest.post(serverProperties.getDiseaseCameraUrl() + "/api/disease_camera/stop_stream").execute()) {
//            return Result.success(true);
//        }
//    }

    @GetMapping("/feed/{stream_id}")
    @Operation(summary = "获取病虫害检测视频流")
    @ApiOperationSupport(order = 3)
    public void cameraFeed(@PathVariable String stream_id,
                           @Parameter(description = "视频流地址，需要进行URL编码，可不传") @RequestParam(required = false) String streamUrl,
                           HttpServletResponse response) {
        if (!StringUtils.hasText(streamUrl)) {
            streamUrl = URLEncoder.encode(serverProperties.getDiseaseCameraStreamUrl(), StandardCharsets.UTF_8);
        }
        VideoFeedUtil.videoFeed(serverProperties.getDiseaseCameraUrl() + "/api/disease_camera/video_feed?stream_id=" + stream_id + "&stream_url=" + streamUrl, 5, response);
    }

    @GetMapping("/latest/{stream_id}")
    @Operation(summary = "获取病虫害最新检测结果")
    @ApiOperationSupport(order = 4)
    public Result<JSONObject> cameraLatest(@PathVariable String stream_id,
                                           @RequestParam(name = "debug", required = false, defaultValue = "false") Boolean debug) {
        CheckLastResultCacheUtil.addTask(stream_id,
                serverProperties.getDiseaseCameraUrl() + "/api/disease_camera/latest_results?debug=" + debug + "&stream_id=" + stream_id,
                agentProperties, agentProperties.getFireAuth());
        return Result.success(CheckLastResultCacheUtil.getResult(stream_id));
    }
}
